#include <cstdio>
#include <iostream>
#include <sched.h>
#include <string>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
#define PATH "."
#define FILENAME "fifo"
#define ERR_EXIT(m) \
    do \
    { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while(0) 
// 创建命名管道类
class NamedFifo {
public:
    NamedFifo(const string& path, const string& name)
        :_path(path), _name(name) {
            _fifoname = _path + "/" + _name;
            umask(0);
            // 创建匿名管道
            int n = mkfifo(_fifoname.c_str(), 0666);
            if(n < 0) {
                ERR_EXIT("mkfifo");
            }else {
                cout << "mkfifo success" << endl;
            }
        }
    ~NamedFifo() {
        // 删除管道文件
        int n = unlink(_fifoname.c_str());
        if(n < 0) {
            ERR_EXIT("unlink");
        }else {
            cout << "remove fifo success" << endl;
        }
    }
private:
    string _name;
    string _path;
    string _fifoname;
};

class FileOper {
public:
    FileOper(const string& path, const string& name)
        :_path(path), _name(name), _fd(-1) {
            _fifoname = _path + "/" + _name;
        }
    void OpenForRead() {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if(_fd < 0) {
            ERR_EXIT("open");
        }else {
            cout << "open fifo success" << endl;
        }
    }
    void OpenForWrite() {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if(_fd < 0) {
            ERR_EXIT("open");
        }else {
            cout << "open fifo success" << endl;
        }
    }
    void Write() {
        string message;
        int cnt = 1;
        pid_t id = getpid();
        while (1) {
            cout << "Please Enter# ";
            getline(cin, message);
            message += (", message number: " + to_string(cnt++) + ", [" + to_string(id) + "]");
            write(_fd, message.c_str(), message.size());
        }
    }
    void Read() {
        while (1) {
            char buffer[1024];
            int n = read(_fd, buffer, sizeof(buffer) - 1);
            if(n > 0) {
                buffer[n] = 0;
                cout << "Client say# " << buffer << endl;
            }else if(n == 0) {
                cout << "client quit! me too" << endl;
                break;
            }else {
                cerr << "read error" << endl;
                break;
            }
        }
    }
    void Close() {
        if(_fd > 0) {
            close(_fd);
        }
    }
    ~FileOper() {
        Close();
    }
private:
    string _name;
    string _path;
    string _fifoname;
    int _fd;
};